package com.project.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.project.MainBoot;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@ComponentScan(basePackageClasses = MainBoot.class)
@MapperScan("com.project.mapper")
@EnableTransactionManagement
public class UserConfig {
    @Bean
    public DataSource getDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/webTest?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useUnicode=true&useSSL=false&allowMultiQueries=true");
        dataSource.setUsername("root");
        dataSource.setPassword("231725");

        dataSource.setMaxActive(100);
        dataSource.setMinIdle(10);
        dataSource.setMaxWait(1000);

        return dataSource;
    }

    /**
     * 设置会话工厂
     *
     * @return 会话工厂
     */
    @Bean
    public SqlSessionFactoryBean getFactoryBean() {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(this.getDataSource());
        factoryBean.setConfigLocation(new ClassPathResource("mybatis.cfg.xml"));
        return factoryBean;
    }

    /**
     * 得到事务管理器
     *
     * @return 事务管理器
     */
    @Bean
    public TransactionManager getTransaction() {
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(this.getDataSource());
        return transactionManager;
    }

}

